package ecustom.common.mode.service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.api.formmode.cache.ModeComInfo;
import com.api.formmode.cache.ModeFormComInfo;
import com.engine.common.util.ServiceUtil;
import com.engine.cube.service.ModeAppService;
import com.engine.cube.service.impl.ModeAppServiceImpl;

import ecustom.common.conn.DB;
import ecustom.common.util.CustomUtil;
import weaver.formmode.setup.ModeRightInfo;
import weaver.hrm.User;
import weaver.hrm.UserManager;

public class ModeService {

	public Integer createBill(int creater, int modeId, String tableName, Map<String, Object> fields) throws Exception {
		setModeFields(creater, modeId, fields);
		DB.conn().save(tableName, fields);
		int id = getMaxId(tableName);
		return id;
	}
	
	public Integer createBillAndShare(int creater, int modeId, String tableName, Map<String, Object> fields) throws Exception {
		int id = createBill(creater, modeId, tableName, fields);
		share(creater, modeId, id);	// 添加新建共享
		return id;
	}

	public static Integer share(int creater, int modeId, int id) throws Exception {
		ModeRightInfo mri = new ModeRightInfo();
		mri.setNewRight(true);
		mri.editModeDataShare(creater, modeId, id);
		return id;
	}
	
	public Integer getMaxId(String tableName) throws Exception {
		return DB.conn().getInteger("SELECT MAX(ID) FROM " + tableName);
	}

	public static String getTableName(int modeId) {
		String formIdStr = new ModeComInfo().getFormId(modeId + "");
		int formId = CustomUtil.getIntCK(formIdStr, "获取表名“modeId=" + modeId + "”失败！");
		return new ModeFormComInfo().getTableName(formId);
	}
	
	/**
	 * 权限重构。
	 */
	public static void resetAllRight(int userId, int modeId) {
		User user = new UserManager().getUserByUserIdAndLoginType(userId, "1");
		ModeAppService srv = ServiceUtil.getService(ModeAppServiceImpl.class, user);
		Map<String, Object> map = new HashMap<>();
		map.put("operation", "resetAllRight");
		map.put("modeid", "" + modeId);
		map.put("righttype", "3");
		map.put("rebulidFlag", "" + modeId);
		map.put("showProgress", "1");
		srv.saveModeRightList(map, user);
	}

	public void setModeFields(int creater, int modeId, Map<String, Object> fields) throws Exception {
		String uuid = UUID.randomUUID().toString();

		// 添加建模表单公共字段值
		fields.put("FORMMODEID", modeId);
		fields.put("MODEDATACREATER", creater);
		fields.put("MODEDATACREATERTYPE", 0);
		fields.put("MODEDATACREATEDATE", CustomUtil.getStringDate("yyyy-MM-dd"));
		fields.put("MODEDATACREATETIME", CustomUtil.getStringDate("HH:mm:ss"));
		fields.put("MODEUUID", uuid);
	}
}